import { ApiCall } from "tsrpc";
import gameCfg from "../../gameCfg";
import MarketManage from "../../core/manage/MarketManage";
import { marketListItem, ReqList, ResList } from "../../shared/api_client/market/PtlList";
import { sort_type } from "../../shared/face/enums";

export default async function (call: ApiCall<ReqList, ResList>) {
    let resList: marketListItem[] = [];
    let findType = call.req.type;
    let findName = call.req.name;
    let findQuality = call.req.quality;
    let page = call.req.page || 1;
    let sortType = call.req.sort;
    const pageSize = 8; // 每页显示数量

    // 过滤符合条件的商品
    for (let i = 0; i < MarketManage.list.length; i++) {
        const e = MarketManage.list[i];
        
        // 类型过滤 - 只有当findType存在时才过滤
        if (findType !== undefined && e.item.type !== findType) {
            continue;
        }
        
        // 名称搜索 - 包含即可，只有当findName存在时才过滤
        if (findName !== undefined && !e.item.name.includes(findName)) {
            continue;
        }
        
        // 品质过滤 - 只有当findQuality存在时才过滤
        if (findQuality !== undefined && e.item.quality !== findQuality) {
            continue;
        }
        
        resList.push({
            _id: e._id,
            name: e.item.name,
            emoji: e.item.emoji,
            icon: e.item.icon || gameCfg.defaultIcon,
            sell_cont: e.item.count,
            sell_price: e.sell_price,
            quality: e.item.quality
        });
    }
    
    // 排序处理
    if (sortType !== undefined) {
        resList.sort((a, b) => {
            switch (sortType) {
                case sort_type.time_up:
                    return a._id.localeCompare(b._id);
                case sort_type.time_down:
                    return b._id.localeCompare(a._id);
                case sort_type.price_up:
                    return a.sell_price - b.sell_price;
                case sort_type.price_down:
                    return b.sell_price - a.sell_price;
                case sort_type.quality_up:
                    return a.quality - b.quality;
                case sort_type.quality_down:
                    return b.quality - a.quality;
                case sort_type.count_up:
                    return a.sell_cont - b.sell_cont;
                case sort_type.count_down:
                    return b.sell_cont - a.sell_cont;
                default:
                    return 0;
            }
        });
    }
    
    // 计算总数
    const total = resList.length;
    
    // 分页处理
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pagedList = resList.slice(startIndex, endIndex);
    
    call.succ({ list: pagedList, total: total });
}
